from rest_framework import status
from rest_framework.exceptions import AuthenticationFailed
from rest_framework.response import Response
from rest_framework.views import exception_handler
from rest_framework_simplejwt.exceptions import InvalidToken, TokenError

import logging

logger = logging.getLogger('django')
def custom_exception_handler(exc, context):
    """
    自定义异常处理
    :param exc:  异常
    :param context:  上下文
    :return: Response对象
    """

    logger.info(f"自定义异常处理,异常信息:{exc}")

    # 先调用DRF 默认的异常处理
    response = exception_handler(exc, context)

    if response is None:
        return response

    # 处理Token相关的异常

    if isinstance(exc, (InvalidToken, AuthenticationFailed, TokenError)):
        logger.info(f"自定义异常处理,Token异常信息:{exc}")
        return Response({
            "code": 401,
            "message": "登录已过期,请重新登录",
            "data": None
        }, status=status.HTTP_401_UNAUTHORIZED)

    # 如果是其他的异常, 统一格式
    return Response({
        "code": response.status_code,
        "message": str(exc),
        'data': None
    }, status=response.status_code)
